﻿using System;
using System.Data;
using Amoo.Code.Common;
using MySql.Data.MySqlClient;

namespace Amoo.Code.Data
{
    public class BaseData:IDisposable
    {

        MySqlConnection _Connection;

        public MySqlConnection Connection
        {
            get 
            {
                if (_Connection == null)
                {
                    _Connection = OpenConnection();
                }

                return _Connection; 
            
            }
            set { Connection = value; }
        }

        protected DataSet ExecuteDataSet(string sqlCommand)
        {
            MySqlDataAdapter da = new MySqlDataAdapter(sqlCommand, Connection);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

        protected IDataReader ExecuteReader(string sqlCommand)
        {
            MySqlCommand cmd = new MySqlCommand(sqlCommand, Connection);
            return cmd.ExecuteReader();
        }

        protected void Execute(string sqlCommand)
        {
            MySqlCommand cmd = new MySqlCommand(sqlCommand, Connection);
            cmd.ExecuteNonQuery();
        }

        protected object ExecuteScalar(string sqlCommand)
        {
            MySqlCommand cmd = new MySqlCommand(sqlCommand, Connection);
            return cmd.ExecuteScalar();
        }

        protected MySqlConnection OpenConnection()
        {
            MySqlConnection connection = new MySqlConnection(Common.Util.Config.ConnectionString);
            connection.Open();
            return connection;
        }

        public void CloseConnection()
        {
            if (Connection != null)
            {
                Connection.Dispose();
                _Connection = null;
            }
        }

        protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                CloseConnection();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
